package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {

        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //获取当前登录人的信息
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.分页条件查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //状态精确查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //频道精确查询
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //查询当前登录用户的文章
        lambdaQueryWrapper.eq(WmNews::getUserId, user.getId());

        //发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = page(page, lambdaQueryWrapper);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1. 入参处理
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNewsEntity = new WmNews();
        BeanUtils.copyProperties(dto, wmNewsEntity);
        //手动处理一下images
        String images = StringUtils.join(dto.getImages(), ",");
        wmNewsEntity.setImages(images);
        //手动处理一下userId
        wmNewsEntity.setUserId(WmThreadLocalUtils.getUser().getId());
        //针对类型为自动的情况进行数据处理
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {
            wmNewsEntity.setType(null);
        }

        //2. 提交或保存文章    -- 新增文章/修改文章
        saveOrUpdateNews(wmNewsEntity);

        //3. 判断是否为草稿: 是草稿，就直接返回； 不是草稿: 关联文章和素材图片的关联关系
        if (dto.getStatus() == WmNews.Status.NORMAL.getCode()) {
            //是草稿，就直接返回
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //4. 不是草稿: 关联文章和素材图片的关联关系
        //4.1 先处理内容中的图片和文章的关联关系
        //第一步： 先解析出文章内容中的所有图片url
        List<String> imageUrls = getAllContentImageUrl(dto.getContent());
        //第二步： 保存图片和文章的关系
        saveMaterialWithNewsRelation(imageUrls,wmNewsEntity.getId(),WemediaConstants.WM_CONTENT_REFERENCE);

        //4.2 先处理封面的图片和文章的关联关系
        handleTopImage(dto,wmNewsEntity,imageUrls);

        //5. 异步调用自动审核功能
        wmNewsAutoScanService.autoScanWmNews(wmNewsEntity.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 处理封面的图片和文章的关联关系
     * 1. 处理封面图片类型为自动的情况：type == -1
     *      规则：  内容图片数量 >= 3 ,则将WmNews的type转为多图3
     *      规则：  3 > 内容图片数量 >= 1 ,则将WmNews的type转为单图1
     *      规则：  内容图片数量 == 0 ,则将WmNews的type转为无图0
     *
     * 2. 保存封面图片和文章的关联关系
     *
     * @param dto
     * @param wmNewsEntity
     * @param imageUrls
     */
    private void handleTopImage(WmNewsDto dto, WmNews wmNewsEntity, List<String> imageUrls) {
        //1. 处理封面图片类型为自动的情况：type == -1
        List<String> images = dto.getImages();
        if (dto.getType() == -1){
            if (imageUrls.size() >= 3){
                //转为多图
                wmNewsEntity.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                List<String> collect = imageUrls.stream().limit(3).collect(Collectors.toList());
                wmNewsEntity.setImages(StringUtils.join(collect,","));
                images = collect;

            }else if (imageUrls.size() >= 1 && imageUrls.size() < 3){
                //转为单图
                wmNewsEntity.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                String url = imageUrls.stream().limit(1).collect(Collectors.toList()).get(0);
                wmNewsEntity.setImages(url);
                images = new ArrayList<>();
                images.add(url);
            }else {
                //转为无图
                wmNewsEntity.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            //更新文章信息
            updateById(wmNewsEntity);
        }


        //2. 保存封面图片和文章的关联关系
        if (images != null) {
            saveMaterialWithNewsRelation(images,wmNewsEntity.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }

    }

    /**
     * 保存图片和文章的关联关系
     * @param imageUrls  图片url
     * @param wmNewsId 文章id
     * @param type  图片类型：0内容  1封面
     */
    private void saveMaterialWithNewsRelation(List<String> imageUrls, Integer wmNewsId, Short type) {

        //校验图片是否存在，如果不存在，则提示用户：素材信息有误！
        //1. 根据图片url查询图片id     select * from wm_material where url in (imageUrls)
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageUrls));
        if (wmMaterials == null || wmMaterials.size() == 0 || imageUrls.size() != wmMaterials.size()){
            throw new CustomException(AppHttpCodeEnum.MATERIAL_NEWS_FAIL);
        }


        //map方法：用来做数据转换
        List<Integer> imageIds = wmMaterials.stream().map((WmMaterial wmMaterial)->{
            Integer id = wmMaterial.getId();
            return id;
        }).collect(Collectors.toList());

        //2. 保存关系
        wmNewsMaterialMapper.saveRelations(imageIds,wmNewsId,type);
    }

    /**
     * 解析文章内容中的所有图片路径并返回
     * @param content 文章内容
     * @return
     */
    private  List<String> getAllContentImageUrl(String content) {
        JSONArray jsonArray = JSON.parseArray(content);
        List<String> urls = new ArrayList<>();

        for (Object obj : jsonArray) {
            JSONObject jsonObject = JSON.parseObject(obj.toString());
            String type = jsonObject.get("type").toString();
            if ("image".equals(type)){
                String url = jsonObject.get("value").toString();
                urls.add(url);
            }
        }
        return urls;
    }

    /**
     * 新增/修改 文章信息
     *
     * @param wmNewsEntity
     */
    private void saveOrUpdateNews(WmNews wmNewsEntity) {
        wmNewsEntity.setCreatedTime(new Date());
        //默认：上架
        wmNewsEntity.setEnable((short) 1);

        //判断是新增还是修改
        if (wmNewsEntity.getId() != null) {
            //修改
            //1. 先删除文章和素材之前的关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNewsEntity.getId()));

            //2. 修改文章信息
            updateById(wmNewsEntity);

        } else {
            //新增
            save(wmNewsEntity);
        }


    }


}